"This is the locale selecting middleware that will look at accept headers"

from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin

from database.models import SystemUserRecord
from utils.config.App import OPEN_MIDDLE_USER_RECORD


class UserRecordMiddleware(MiddlewareMixin):
    """
        用户行为记录
    """
    response_redirect_class = HttpResponseRedirect

    def process_request(self, request):
        pass

    def process_view(self, request, callback, callback_args, callback_kwargs):
        if OPEN_MIDDLE_USER_RECORD:
            _path_info = request.META.get('PATH_INFO') or ""
            _method = request.META.get('REQUEST_METHOD') or "GET"
            _ip_address = request.META.get('REMOTE_ADDR') or "0.0.0.0"

            if _method.upper() != "GET":
                user = request.user
                if user.pk is None:
                    user = None

                _data = request.body.decode(encoding="utf-8")
                SystemUserRecord.objects.create(path=_path_info,
                                                method=_method,
                                                user=user,
                                                ip_address=_ip_address,
                                                data=_data)
